package com.defysoft.waukids.notice;

import java.util.ArrayList;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

import com.defysoft.waukids.BaseFragment;
import com.defysoft.waukids.Data_Type.BC_NOTICE;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.R;
import com.defysoft.waukids.adapter.Adapter_Notice_L;
import com.google.android.gms.internal.el;

public class Notice_School_F extends BaseFragment implements OnClickListener,OnScrollListener {
	View view;
	ListView listView;
	final int FIRST_SEARCH = 1; // 처음 공지리스트 불러오기
	final int MORE_SEARCH = 2; // 더보기 공지리스트 불러오기

	private final int NONE_NOTICE = 9; // 공지없음.
	private final int SUCCESS_SEARCH = 10; // 공지있음.

	final int SUCCESS_MORE_SEARCH = 8; // 더보기있음.
	final int NONE_MORE_NOTICE = 7; // 더보기없음.
	private SharedPreferences member;
	private SharedPreferences student;
	public ArrayList<BC_NOTICE> list;
	Adapter_Notice_L adapter; // 공지 어댑터.
	// 더보기
	boolean ListViewLock;
	int count = 0;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == TOOLBAR_BACK) {
			startNetwork(FIRST_SEARCH);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.notice_school_f, null);
		student = this.getActivity().getSharedPreferences("student", Context.MODE_PRIVATE);
		member = this.getActivity().getSharedPreferences("member",Context.MODE_PRIVATE);
		setStartData();
		return view;
	}

	@Override
	public void setStartData() {
		super.setStartData();
		startDIal();
		listView = (ListView) view.findViewById(R.id.NOTICE_SCHOOL_LV);
		startNetwork(FIRST_SEARCH);
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		if (firstThread != null) {
			firstThread.interrupt();
		}
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case FIRST_SEARCH:
					mainThread();
					break;

				case MORE_SEARCH:
					moreThread();
					break;
				}
			}
		});
		firstThread.start();
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // thread 에러 메세지
			if (firstThread != null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(getActivity(), (String) _message.obj,Toast.LENGTH_LONG).show();
			break;
		case NONE_NOTICE: // 공지없음.
			if (firstThread != null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(getActivity(), "등록된 공지가 없습니다.", Toast.LENGTH_LONG).show();
			break;
		case SUCCESS_SEARCH: // 공지있음.
			if (firstThread != null) {firstThread.interrupt();}
			listView.setOnScrollListener(this); // 더보기 리스너 세팅.
			adapter = new Adapter_Notice_L(getActivity(), 0, list,getActivity().getLayoutInflater());
			listView.setAdapter(adapter);
			endDIal();
			break;
		case SUCCESS_MORE_SEARCH: // 더보기 있음.
			if (firstThread != null) {firstThread.interrupt();}
			adapter.list.addAll(list);
			adapter.notifyDataSetChanged();
			ListViewLock = false;
			endDIal();
			break;
		case NONE_MORE_NOTICE: // 더보기 없음.
			if (firstThread != null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(getActivity(), "마지막 공지입니다.", Toast.LENGTH_LONG).show();
			break;
		}
	}

	public void mainThread(){
		try{
			JSONObject jsonObject ;
			if(member.getString("Mem_Rank", "1").equals("3")){
				jsonObject = new JSONObject(publicHttpCallback(HTTP_SELECT_NOTICE_SCHOOL, "school="+student.getString("FK_Sch_Stu_Code", "")+"&limit=5"));
			}else {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_SELECT_NOTICE_SCHOOL, "school="+member.getString("FK_Sch_Mem_Code", "")+"&limit=5"));
			}
			if (jsonObject.getBoolean("success")) {	
				
				
					this.list=JsonParser.SelectNotice(jsonObject.getString("payload"));
					count = jsonObject.getInt("count");
					onNetworkCallback(SUCCESS_SEARCH,"" );
				
			} else {
				onNetworkCallback(NONE_NOTICE, "");
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main"+e.toString());
		};	
	}

	public void moreThread() { // 더보기
		try {
			JSONObject jsonObject = null;
			jsonObject = new JSONObject(publicHttpCallback(
					HTTP_SELECT_NOTICE_SCHOOL,
					"school=" + member.getString("FK_Sch_Mem_Code", "")
							+ "&limit=" + adapter.list.size() + ",5"));
			if (jsonObject.getBoolean("success")) {
				this.list = JsonParser.SelectNotice(jsonObject
						.getString("payload"));
				count = jsonObject.getInt("count");
				onNetworkCallback(SUCCESS_MORE_SEARCH, "");
			} else {
				onNetworkCallback(NONE_MORE_NOTICE, "");
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	// 더보기
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		int lastItem = totalItemCount - visibleItemCount;
		if (firstVisibleItem >= lastItem && totalItemCount != 0
				&& ListViewLock == false) {
			if (adapter.list.size() < count) {
				ListViewLock = true;
				startNetwork(MORE_SEARCH);
			}
		}
	}

}
